package cn.li.security.json.handle;


import cn.li.security.json.bean.Result;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public abstract class BaseJSONHandler {

    public static final String APPLICATION_JSON_CHARSET_UTF_8 = "application/json; charset=utf-8";
    public static final String CHARACTER_ENCODING = "UTF-8";


    private ObjectMapper objectMapper;

    public BaseJSONHandler(ObjectMapper objectMapper){
        this.objectMapper = objectMapper;
    }

    public void writeResult(HttpServletResponse response , Result result) throws IOException {
        response.setStatus(200);
        response.setCharacterEncoding(CHARACTER_ENCODING);
        response.setContentType(APPLICATION_JSON_CHARSET_UTF_8);
        PrintWriter printWriter = response.getWriter();
        printWriter.write(objectMapper.writeValueAsString(result));
        printWriter.flush();
    }


}
